import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  Inject,
} from '@nestjs/common';
import { Response } from 'express';
import { Logger } from '@/logger/logger';
import { responseMessage } from '@/utils';

// @Catch() 装饰器绑定所需的元数据到异常过滤器上。它告诉 Nest这个特定的过滤器正在寻找
@Catch(HttpException)
export class HttpExceptionsFilter implements ExceptionFilter {
  @Inject(Logger)
  private logger: Logger;

  // constructor(private logger:Logger)
  catch(exception: any, host: ArgumentsHost) {
    // 获取上下文
    const ctx = host.switchToHttp();
    // 获取响应体
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest();
    // 获取状态码
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse();
    const logFormat = `
##############################################################################################################
Request original url: ${request.originalUrl}
Method: ${request.method}
IP: ${request.ip}
Status code: ${status}
Response: ${
      exception.toString() +
      `（${exceptionResponse?.message || exception.message}）`
    }
##############################################################################################################
`;
    if (this.logger) {
      this.logger.error(logFormat, 'HttpException filter ');
    } else {
      console.log('httperror', logFormat);
    }
    // 自定义异常返回体
    response
      .status(status)
      .json(responseMessage(null, exception.message, status));
  }
}
